import React, { Component } from 'react'
import { Alert, StatusBar, DeviceEventEmitter, CheckBox, CameraRoll, Image, TouchableOpacity, ScrollView, BackHandler, View, Text } from 'react-native'
import Button from '../Components/Button'
import Icon from 'react-native-vector-icons/FontAwesome'
var ImagePicker = require('react-native-image-picker')
import { connect } from 'react-redux'
import { NavigationActions } from 'react-navigation'

import * as WeChat from 'react-native-wechat';
//import Auth from '../Lib/Auth';

import UserActions from '../Redux/UserRedux'
import AppConfig from '../Config/AppConfig'
const domain = AppConfig.domain

// Styles
import styles from './Styles/UserInfoScreenStyle'

class UserInfoScreen extends Component {
  static navigationOptions = {
    title: '我的信息'
  }
  constructor(props) {
    super(props)
    this.state = {
      isBind: this.props.user.is_wx,
      avatar: this.props.user.head_img
    }
  }

  _auth = () => {
    WeChat.sendAuthRequest('snsapi_userinfo')
      .then((result) => {
        if (result.errCode == '0') {
          fetch(`http://www.jiankangdaowei.com/api/user/bind?code=${result.code}`, {
            headers: {
              'token': this.props.user.token, 
            }
          })
            .then(response => response.json())
            .then(responseJson => {
              if(responseJson.code == 1){
                this.setState({isBind:true});
                this.props.getUser(this.props.user.token);
              }
            })
        }
      }).catch((error) => {
      })
  }

  _pressEvent = () => {
    this.props.logout()
    const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'LaunchScreen'})
      ]
    })
    this.props.navigation.dispatch(resetAction)
    DeviceEventEmitter.emit('logout')
  }
  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  getAvatar() {
    const options = {
      title: '选择头像',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '从手机相册选择',
      mediaType: 'photo',
      maxWidth: 120,
      maxHeight: 120,
      opacity: 0.85,
      storageOptions: {
        skipBackup: true,
        path: 'images'
      }
    }
    //CameraRoll.getPhotos({
    //  first: 1,
    //  assetType: 'All'
    //})
    //.then(result => console.tron.log(result))
    ImagePicker.showImagePicker(options, (response) => {
      if(response.uri) {
        this.setState({avatar:response.uri})
        console.tron.log(response.data)
        this.props.updateUser(
          this.props.user.token,
          'head_img',
          'data:image/png;base64,'+response.data)
      }
    })
  }
  render () {
    if(!this.props.user) {
      return null
    }
    const { navigate } = this.props.navigation
    return (
      <ScrollView style={styles.container}>
        <StatusBar translucent={false} barStyle='dark-content' backgroundColor='white' />
        <View style={styles.section}>
          <TouchableOpacity
            onPress={()=>this.getAvatar()}
            style={styles.item}>
            <Text>头像</Text>
            <View style={styles.right}>
              <Image
                style={styles.avatar}
                source={{uri:this.state.avatar}} />
              <Icon style={styles.rightIcon} name='chevron-right' />
            </View>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={()=>navigate('UserUpdateScreen',{title:'昵称',field:'nickname'})}
            style={styles.item}>
            <Text>昵称</Text>
            <View style={styles.right}>
              <Text>{this.props.user.nickname}</Text>
              <Icon style={styles.rightIcon} name='chevron-right' />
            </View>
          </TouchableOpacity>
          <View style={styles.item}>
            <Text>手机号码</Text>
            <View style={styles.right}>
              <Text>{this.props.user.mobile}</Text>
            </View>
          </View>
          <View style={styles.item}>
            <Text>微信账号</Text>
            {!this.state.isBind ? (
              <TouchableOpacity style={styles.right} onPress={this._auth}>
                <Text>绑定</Text>
              </TouchableOpacity>
            ) : (
              <View style={styles.right}>
                <Text>已绑定</Text>
              </View>
            )}
          </View>
        </View>
        <View style={styles.section}>
          <TouchableOpacity
            onPress={()=>this.props.navigation.navigate('AddressScreen')}
            style={styles.item}>
            <Text>地址管理</Text>
            <Icon style={styles.rightIcon} name='chevron-right' />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={()=>navigate('PasswordScreen')}
            style={styles.item}>
            <Text>修改密码</Text>
            <Icon style={styles.rightIcon} name='chevron-right' />
          </TouchableOpacity>
        </View>
        <View style={{padding:10}}>
          <Button title='退出' onPress={this._pressEvent} />
        </View>
      </ScrollView>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user.payload
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getUser: (token, deviceId) => dispatch(UserActions.userRequest(token, deviceId)),
    updateUser: (token,field,value)=>dispatch(UserActions.updateUserRequest(token,field,value)),
    logout: () => dispatch(UserActions.logout())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(UserInfoScreen)
